package cn.tedu.wenzhang2.controller;


import cn.tedu.wenzhang2.base.response.JsonResult;
import cn.tedu.wenzhang2.base.response.StatusCode;
import cn.tedu.wenzhang2.mapper.UserMapper;
import cn.tedu.wenzhang2.pojo.dto.UserLoginDTO;
import cn.tedu.wenzhang2.pojo.dto.UserRegDTO;
import cn.tedu.wenzhang2.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("v1/users/")
@Api(tags = "用户模块")
public class UserController {
    @Autowired(required = false)
    private UserMapper userMapper;

    @PostMapping("reg")
    @ApiOperation(value="注册")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO){
        UserVO userVO=userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO==null){
            int i = userMapper.insertUser(userRegDTO);
            if (i==1)
                return JsonResult.ok();
            return JsonResult.notok();
        }
        return new JsonResult(StatusCode.USERNAME_EXITS);
    }


    @PostMapping("login")
    @ApiOperation(value="登录")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        UserVO userVO=userMapper.selectByUsername(userLoginDTO.getUsername());
        if(userVO!=null){
            if(userVO.getPassword().equals(userLoginDTO.getPassword())){
                session.setAttribute("user",userVO);
                return JsonResult.ok();
            }
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROE);
        }
        return new JsonResult(StatusCode.USERNAME_ERROE);
    }



}
